import 'package:flutter/foundation.dart';

wxLog(dynamic obj, {StackTrace currentTrace}) {
  LogUtil._d(obj,currentTrace:currentTrace);
}

class LogUtil {
  static int _limitLength = 800;

  static void init({int limitLength}) {
    _limitLength = limitLength ??= _limitLength;
  }

  //仅Debug模式可见
  // eg: LogUtil.d("12345666", currentTrace: StackTrace.current);
  static void _d(dynamic obj, {StackTrace currentTrace}) {
    if (!kReleaseMode) {
      if (currentTrace != null) {
        _Trace programInfo = _Trace(currentTrace);
        _log("${programInfo.fileName}:${programInfo.lineNumber} " +
            obj.toString());
      } else {
        _log(obj.toString());
      }
    }
  }

  static void v(dynamic obj) {
    _log(obj.toString());
  }

  static void _log(String msg) {
    _logEmptyLine();
    if (msg.length < _limitLength) {
      print("${DateTime.now()}: " + msg);
    } else {
      segmentationLog("${DateTime.now()}: " + msg);
    }
  }

  static void segmentationLog(String msg) {
    var outStr = StringBuffer();
    for (var index = 0; index < msg.length; index++) {
      outStr.write(msg[index]);
      if (index % _limitLength == 0 && index != 0) {
        print(outStr);
        outStr.clear();
        var lastIndex = index + 1;
        if (msg.length - lastIndex < _limitLength) {
          var remainderStr = msg.substring(lastIndex, msg.length);
          print(remainderStr);
          break;
        }
      }
    }
  }

  static void _logEmptyLine() {
    print("");
  }
}

class _Trace {
  final StackTrace _trace;

  String fileName;
  int lineNumber;
  int columnNumber;

  _Trace(this._trace) {
    _parseTrace();
  }

  void _parseTrace() {
    var traceString = this._trace.toString().split("\n")[0];
    var indexOfFileName = traceString.indexOf(RegExp(r'[A-Za-z_]+.dart'));
    var fileInfo = traceString.substring(indexOfFileName);
    var listOfInfos = fileInfo.split(":");
    this.fileName = listOfInfos[0];
    this.lineNumber = int.parse(listOfInfos[1]);
    var columnStr = listOfInfos[2];
    columnStr = columnStr.replaceFirst(")", "");
    this.columnNumber = int.parse(columnStr);
  }
}



